
import { getToken, setToken, removeToken } from '../../utils/token'

// 默认的state
const getDefaultState = () => {
    return {
        // 当前用户token
        token: getToken(),
        // 当前用户名称
        name: '',
        // 当前用户头像
        avatar: ''
    }
}

// 定义state
const state = getDefaultState()

// 定义mutations
const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_USERINFO: (state, info) => {
        state.name = info.name
        state.avatar = info.avatar
    }
}

// 定义actions方法
const actions = {
    // 登录
    userLogin({ commit }, { username, password }) {
        return new Promise((resolve, reject) => {
            if (username === 'admin' && password === 'admin') {
                setToken('token123')
                resolve()
            }else{
                reject(new Error("登录信息失败"))
            }
        })
    },
    // 重置token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() 
            commit('RESET_STATE')
            resolve()
        })
    },
    getUserInfo({ commit }) {
        // 获取当前token的用户信息。
        return new Promise( (resolve, reject) => {
            const info = {
                name: 'zhangsan',
                avatar: ''
            }
            commit('SET_USERINFO', info)
            resolve()
        } )
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}